<script setup>
import { onMounted, onUnmounted, ref, nextTick, computed } from 'vue';
import {
  Layout,
  LayoutHeader,
  LayoutContent,
  LayoutFooter,
  Space,
  Button,
  Table,
  Popconfirm,
  message,
  Drawer,
  Form,
  FormItem,
  Input,
  InputNumber,
  Select,
  Radio,
  RadioGroup,
  Upload,
  Tooltip,
  Progress,
  Switch,
} from 'ant-design-vue';

import {
  knowledgeList,
  knowledgeDelete,
  knowledgeSave,
  knowledgeDetail,
  knowledgeFileDelete,
  knowledgeFragmentList,
  getRagflowFragments,
  uploadToRagflow,
  checkRagflowStatus,
  syncRagflowDatasets,
} from '#/api/system/knowledgeBase';

import { useAppConfig } from '@vben/hooks';
import { useAccessStore } from '@vben/stores';

const { apiURL, clientId } = useAppConfig(
  import.meta.env,
  import.meta.env.PROD,
);
const accessStore = useAccessStore();
const uploadUrl = `${apiURL}/knowledge/attach/upload`;
// 使用upload组件只能这样上传
let kid = ref('');
const headers = {
  Authorization: `Bearer ${accessStore.accessToken}`,
  clientId,
};

const uploading = ref(false);
const uploadProgress = ref(0);
const uploadStatus = ref('');
function handleChange(info) {
  const file = info.file;
  const status = file?.status;
  // const url = file?.response?.data.url;
  const name = file?.name;

  switch (status) {
    case 'uploading': {
      if (!uploading.value) {
        uploading.value = true;
        uploadProgress.value = 0;
        uploadStatus.value = '文件上传中...';
      }
      // 模拟进度更新，让进度条更平滑
      if (file.percent) {
        uploadProgress.value = Math.round(file.percent);
      } else {
        // 如果没有percent，模拟进度
        if (uploadProgress.value < 90) {
          uploadProgress.value += Math.random() * 10;
        }
      }

      break;
    }
    case 'done': {
      // http 200会走到这里  需要再次判断
      const { response } = file;
      const { code, data, msg = '服务器错误' } = response;
      if (code === 0) {  // 改为code === 0，因为后端返回的是R对象，code=0表示成功
        uploadProgress.value = 100;
        uploadStatus.value = '文件上传成功，正在解析...';
        // 延迟刷新文件列表，确保后端已经处理完成
        setTimeout(() => {
          getDetail(kid.value);
        }, 500);
        // 开始轮询解析进度
        startPollingParseProgress();
        setTimeout(() => {
          uploading.value = false;
          uploadProgress.value = 0;
          uploadStatus.value = '';
        }, 2000);
      } else {
        uploadStatus.value = '文件上传失败！';
        setTimeout(() => {
          uploading.value = false;
          uploadProgress.value = 0;
          uploadStatus.value = '';
        }, 2000);
      }

      break;
    }
    case 'error': {
      uploadStatus.value = '文件上传失败！';
      setTimeout(() => {
        uploading.value = false;
        uploadProgress.value = 0;
        uploadStatus.value = '';
      }, 2000);

      break;
    }
  }
}

const data = ref([]);
const drawerVisible = ref(false);
const defaultFormData = {
  share: '0',
  kname: '',
  description: '',
};
const formData = ref({ ...defaultFormData });
const getVector = ref([
  { label: 'weaviate', value: 'weaviate' },
  { label: 'milvus', value: 'milvus' },
]);

const getVectorModel = ref([
  { label: 'text-embedding-3-small', value: 'text-embedding-3-small' },
]);

onMounted(() => {
  getList();
  checkRagflowServiceStatus();
});

// 检查Ragflow服务状态
const checkRagflowServiceStatus = () => {
  checkRagflowStatus().then((res) => {
    ragflowStatus.value = res.data;
  }).catch(() => {
    ragflowStatus.value = false;
  });
};

const getList = () => {
  knowledgeList().then((res) => {
    data.value = res.rows;
  }).catch((error) => {
    console.error('获取知识库列表失败:', error);
    message.error('获取知识库列表失败');
  });
};

const headerStyle = {
  textAlign: 'right',
  height: 64,
  lineHeight: '64px',
  backgroundColor: '#fff',
};

const contentStyle = {
  backgroundColor: '#fff',
  flex: '1',
  overflow: 'auto', // 内容过多时可滚动
};

const columns = [
  { title: '编号', dataIndex: 'kid', key: 'kid' },
  { title: '知识名称', dataIndex: 'kname', key: 'kname' },
  { title: '知识描述', dataIndex: 'description', key: 'description' },
  { title: '操作', key: 'action' },
];

// Ragflow相关状态
const ragflowStatus = ref(false);
const ragflowUploading = ref(false);

// 新增
const handleAdd = () => {
  formData.value = { ...defaultFormData };
  drawerVisible.value = true;
};

// 删除
const handleDelete = (record) => {
  knowledgeDelete(record.kid).then((res) => {
    // 响应拦截器已经处理了code=200的情况
    // res可能是字符串（成功消息）或undefined
    console.log('删除响应:', res);
    
    message.success('删除成功');
    getList(); // 刷新知识库列表
  }).catch((error) => {
    console.error('删除知识库失败:', error);
    // 如果后端删除成功但返回格式异常，只是本地刷新失败
    // 这种情况下不显示错误，因为后端已经删除了
    if (error.message && !error.message.includes('code')) {
      message.error('删除失败：' + error.message);
    }
    // 尝试刷新列表（即使失败也不影响用户）
    try {
      getList();
    } catch (e) {
      console.warn('刷新列表失败，请手动刷新页面');
    }
  });
};

// 同步RAGFlow数据集
const syncing = ref(false);
const handleSyncRagflow = () => {
  syncing.value = true;
  message.loading({ content: '正在同步RAGFlow数据集...', duration: 0, key: 'sync' });
  syncRagflowDatasets().then((res) => {
    console.log('同步响应（完整）:', res);
    
    // 检查响应是否为空
    if (!res) {
      message.destroy('sync');
      message.error('同步失败：服务器未返回数据');
      return;
    }
    
    // 由于响应拦截器的处理，res可能是：
    // 1. 如果后端返回 {code: 200, msg: "成功同步 X 个", data: "X"}，拦截器会返回 data（即字符串"X"）
    // 2. 所以 res 直接是同步数量（字符串或数字）
    let countStr = '0';
    if (typeof res === 'string' || typeof res === 'number') {
      countStr = String(res);
    } else if (typeof res === 'object' && res !== null) {
      // 兼容性：如果返回的是对象，尝试获取 data 字段
      countStr = String(res.data || res.count || '0');
    }
    const countNum = parseInt(countStr) || 0;
    message.destroy('sync');
    
    if (countNum === 0) {
      message.info('目前知识库已全部同步，无需更新');
    } else {
      message.success(`同步成功！新增 ${countStr} 个知识库`);
      getList(); // 刷新知识库列表
    }
  }).catch((error) => {
    console.error('同步失败:', error);
    message.destroy('sync');
    message.error('同步失败：' + (error.message || '网络错误'));
  }).finally(() => {
    syncing.value = false;
  });
};

// 附件
const fileVisible = ref(false);
const fileData = ref([]);
// 处理参数配置
const processConfigVisible = ref(false);
const processConfig = ref({
  separator: '\\n\\n\\n',
  textBlockSize: 400,
  overlapChar: 0,
  retrieveLimit: 5,
  questionSeparator: '',
  vectorModel: 'text-embedding-3-small',
  chunkingMethod: 'naive', // 切片方法
});

// 切片方法选项
const chunkingMethodOptions = [
  { label: '简单切片 (Naive)', value: 'naive' },
  { label: '智能切片 (Smart)', value: 'smart' },
  { label: '手动切片 (Manual)', value: 'manual' },
  { label: '正则切片 (Regex)', value: 'regex' },
  { label: '表格切片 (Table)', value: 'table' },
];

// 上传前的处理
const beforeUpload = (file) => {
  console.log('准备上传文件:', file.name);
  console.log('当前配置参数:', processConfig.value);
  return true;
};

// 上传数据（带处理参数）
const uploadData = computed(() => ({
  kid: kid.value,
  separator: processConfig.value.separator,
  textBlockSize: processConfig.value.textBlockSize,
  overlapChar: processConfig.value.overlapChar,
  retrieveLimit: processConfig.value.retrieveLimit,
  questionSeparator: processConfig.value.questionSeparator,
  vectorModel: processConfig.value.vectorModel,
  chunkingMethod: processConfig.value.chunkingMethod,
}));

const handleAttachment = (record) => {
  getDetail(record.kid);
  fileVisible.value = true;
  kid.value = record.kid;
};

// 关闭附件弹窗时刷新知识库列表
const handleFileDrawerClose = () => {
  fileVisible.value = false;
  getList(); // 刷新知识库列表
};
const getDetail = (id) => {
  knowledgeDetail(id).then((res) => {
    // 确保每个文件都有正确的启用状态（默认启用）
    const rows = (res.rows || []).map(item => ({
      ...item,
      enable: item.enable === 0 ? 1 : (item.enable || 1), // 确保启用状态默认为1
    }));
    fileData.value = rows;
  }).catch((error) => {
    console.error('查询附件失败:', error);
    fileData.value = [];
  });
};
// 附件表格
const fileColumns = [
  { 
    title: '名称', 
    dataIndex: 'docName', 
    key: 'docName', 
    ellipsis: true, 
    width: 300,
    sorter: (a, b) => {
      const nameA = a.docName || '';
      const nameB = b.docName || '';
      return nameA.localeCompare(nameB, 'zh-CN');
    }
  },
  { 
    title: '上传日期', 
    dataIndex: 'createTime', 
    key: 'createTime', 
    width: 180,
    sorter: (a, b) => {
      const timeA = a.createTime ? new Date(a.createTime).getTime() : 0;
      const timeB = b.createTime ? new Date(b.createTime).getTime() : 0;
      return timeA - timeB;
    }
  },
  { title: '启用', dataIndex: 'enable', key: 'enable', width: 80 },
  { title: '分块数', dataIndex: 'chunkCount', key: 'chunkCount', width: 100 },
  { title: '解析', dataIndex: 'parseStatus', key: 'parseStatus', width: 250 },
  { title: '动作', key: 'action', width: 200, fixed: 'right' },
];

// 获取文件图标 - 根据文件类型返回对应的图标
const getFileIcon = (docType) => {
  const iconMap = {
    'pdf': '📄',  // PDF文件
    'doc': '📝',  // Word文档
    'docx': '📝', // Word文档
    'xls': '📊',  // Excel表格
    'xlsx': '📊', // Excel表格
    'txt': '📄',  // 文本文件
    'csv': '📊',  // CSV文件
    'json': '📋', // JSON文件
    'pptx': '📊', // PowerPoint
    'ppt': '📊',  // PowerPoint
  };
  const type = docType?.toLowerCase();
  // 如果是PDF，返回红色PDF图标样式
  if (type === 'pdf') {
    return '🔴📄'; // 红色PDF图标
  }
  return iconMap[type] || '📄';
};

// 格式化日期
const formatDateTime = (dateStr) => {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
};

// 附件删除
const handleDeleteFile = (record) => {
  knowledgeFileDelete(record.docId).then((res) => {
    if (res.code === 0) {
      message.success('删除成功');
      getDetail(kid.value); // 刷新文件列表
    } else {
      message.error('删除失败：' + (res.msg || '未知错误'));
    }
  }).catch((error) => {
    console.error('删除文件失败:', error);
    message.error('删除失败：网络错误');
  });
};

// 启用/禁用切换
const handleEnableChange = (record, checked) => {
  // TODO: 调用后端API更新启用状态
  console.log('切换启用状态:', record.docId, checked);
  // 这里可以调用后端API更新状态
  record.enable = checked ? 1 : 0;
};

// 轮询解析进度
let pollingInterval = null;
const startPollingParseProgress = () => {
  // 清除之前的轮询
  if (pollingInterval) {
    clearInterval(pollingInterval);
  }
  
  let pollCount = 0;
  const maxPolls = 60; // 最多轮询60次（5分钟，每次5秒）
  
  // 立即执行一次刷新
  setTimeout(() => {
    getDetail(kid.value);
  }, 1000);
  
  pollingInterval = setInterval(() => {
    pollCount++;
    if (pollCount > maxPolls) {
      clearInterval(pollingInterval);
      pollingInterval = null;
      return;
    }
    
    // 刷新文件列表以获取最新解析进度
    getDetail(kid.value);
    
    // 检查是否所有文件都解析完成
    const allParsed = fileData.value.every(file => 
      file.parseProgress === 100 || file.parseError === true
    );
    
    if (allParsed && fileData.value.length > 0) {
      clearInterval(pollingInterval);
      pollingInterval = null;
    }
  }, 3000); // 每3秒轮询一次，更及时
};

// 组件卸载时清除轮询
onUnmounted(() => {
  if (pollingInterval) {
    clearInterval(pollingInterval);
    pollingInterval = null;
  }
});

// Ragflow上传文件
const handleRagflowUpload = (file) => {
  ragflowUploading.value = true;
  uploadToRagflow(kid.value, file).then((res) => {
    message.success('文件上传到Ragflow成功！');
    ragflowUploading.value = false;
    // 自动刷新文件列表
    getDetail(kid.value);
  }).catch(() => {
    message.error('文件上传到Ragflow失败！');
    ragflowUploading.value = false;
  });
  return false; // 阻止默认上传行为
};

// 知识片段
const fileFragmentVisible = ref(false);
const fileFragmentColumns = ref([]);
const fileFragmentData = ref([]);
const handleFragment = async (record) => {
  try {
    // 尝试从RAGFlow获取文档信息
    const response = await getRagflowFragments(record.id);
    console.log('RAGFlow返回完整数据:', JSON.stringify(response, null, 2));
    
    // response 可能是 { code: 0, data: {...} } 格式，也可能是直接的数据
    const data = response?.data || response;
    
    // 检查是否是RAGFlow返回的数据（有documentInfo字段）
    if (data && data.documentInfo) {
      console.log('✓ 从RAGFlow获取到文档信息');
      
      // 显示提示信息
      if (data.chunkCount) {
        message.success(`该文档包含 ${data.chunkCount} 个知识片段`);
      } else {
        message.info('该文档正在解析中...');
      }
      
      // 动态设置表格列
      fileFragmentColumns.value = [
        { title: '文档ID', dataIndex: 'id', key: 'id', width: 300 },
        { title: '文档名', dataIndex: 'name', key: 'name', width: 200 },
        { title: '片段数量', dataIndex: 'chunk_count', key: 'chunk_count', width: 100 },
        { title: '状态', dataIndex: 'status', key: 'status', width: 80 },
        { title: '处理时长(秒)', dataIndex: 'process_duration', key: 'process_duration', width: 120 },
      ];
      fileFragmentData.value = [data.documentInfo];
      
      // 显示RAGFlow链接
      if (data.ragflowUrl) {
        message.info({
          content: `查看完整知识片段: ${data.ragflowUrl}`,
          duration: 10,
        });
      }
    } else {
      console.warn('未收到RAGFlow数据，回退到本地');
      message.warning('未找到RAGFlow文档信息，使用本地数据');
      // 回退到本地数据库
      fileFragmentColumns.value = [
        { title: '片段编号', dataIndex: 'fid', key: 'fid' },
        { title: '片段内容', dataIndex: 'content', key: 'content' },
      ];
      const localRes = await knowledgeFragmentList(record.docId);
      fileFragmentData.value = localRes.rows || [];
    }
  } catch (error) {
    console.error('获取知识片段失败:', error);
    message.error('获取知识片段失败: ' + error.message);
    // 回退到本地数据库
    fileFragmentColumns.value = [
      { title: '片段编号', dataIndex: 'fid', key: 'fid' },
      { title: '片段内容', dataIndex: 'content', key: 'content' },
    ];
    try {
      const localRes = await knowledgeFragmentList(record.docId);
      fileFragmentData.value = localRes.rows || [];
    } catch (e) {
      fileFragmentData.value = [];
    }
  }
  fileFragmentVisible.value = true;
};

// 关闭知识片段弹窗时刷新文件列表
const handleFragmentDrawerClose = () => {
  fileFragmentVisible.value = false;
  getDetail(kid.value); // 刷新文件列表
};

// 添加表单引用
const formRef = ref();

// 修改提交处理函数
const handleSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      knowledgeSave(formData.value).then((res) => {
        message.success('添加成功');
        getList();
        drawerVisible.value = false;
      });
    })
    .catch((error) => {
      console.log('表单校验失败:', error);
    });
};

// 关闭创建知识库弹窗时刷新列表
const handleDrawerClose = () => {
  drawerVisible.value = false;
  getList(); // 刷新知识库列表
};
</script>

<template>
  <div>
    <Space direction="vertical" :style="{ width: '100%' }" :size="[0, 48]">
      <Layout style="height: 100%">
        <LayoutHeader :style="headerStyle">
          <Space>
            <Button type="primary" @click="handleAdd">新增</Button>
            <Button type="primary" @click="handleSyncRagflow" :loading="syncing">
              同步RAGFlow
            </Button>
          </Space>
        </LayoutHeader>
        <LayoutContent :style="contentStyle">
          <Table :columns="columns" :data-source="data">
            <template #bodyCell="{ column, record }">
              <span v-if="column.key === 'action'">
                <Popconfirm
                  title="确定删除吗？"
                  ok-text="是"
                  cancel-text="否"
                  @confirm="handleDelete(record)"
                >
                  <Button type="primary" danger style="margin-right: 10px">
                    删除
                  </Button>
                </Popconfirm>

                <Button type="primary" @click="handleAttachment(record)"
                  >附件</Button
                >
                
                <Upload
                  v-if="ragflowStatus"
                  :show-upload-list="false"
                  accept=".txt,.pdf,.docx,.pptx,.xlsx,.xls,.csv,.json"
                  :before-upload="handleRagflowUpload"
                  style="margin-left: 10px; display: inline-block"
                >
                  <Button 
                    type="primary" 
                    :loading="ragflowUploading"
                  >
                    Ragflow上传
                  </Button>
                </Upload>
              </span>
            </template>
          </Table>
        </LayoutContent>
      </Layout>
    </Space>

    <Drawer
      title="知识片段"
      :visible="fileFragmentVisible"
      @close="handleFragmentDrawerClose"
      :width="1000"
    >
      <Table :columns="fileFragmentColumns" :data-source="fileFragmentData">
        <template #bodyCell="{ column, record }">
          <Tooltip v-if="column.key === 'content'" :title="record.content">
            <span>
              {{
                record.content.length > 50
                  ? record.content.slice(0, 50) + '...'
                  : record.content
              }}
            </span>
          </Tooltip>
        </template>
      </Table>
    </Drawer>

    <Drawer
      title="知识库附件"
      :visible="fileVisible"
      @close="handleFileDrawerClose"
      :width="1000"
    >
      <Button 
        type="primary" 
        style="margin-bottom: 10px; margin-right: 10px"
        @click="processConfigVisible = true"
      >
        配置处理参数
      </Button>
      <Upload
        :action="uploadUrl"
        :headers="headers"
        :show-upload-list="false"
        accept=".txt,.pdf,.docx,.pptx,.xlsx,.xls,.csv,.json"
        multiple
        name="file"
        :data="uploadData"
        :before-upload="beforeUpload"
        @change="handleChange"
      >
        <a-button type="primary" style="margin-bottom: 10px">
          文件上传
        </a-button>
      </Upload>
      
      <!-- 上传进度条 -->
      <div v-if="uploading" style="margin-top: 10px; margin-bottom: 10px;">
        <Progress 
          :percent="uploadProgress" 
          :status="uploadProgress === 100 ? 'success' : 'active'"
          :format="() => uploadStatus"
          :stroke-color="uploadProgress === 100 ? '#52c41a' : '#1890ff'"
          :trail-color="'#f0f0f0'"
        />
      </div>
      <Table :columns="fileColumns" :data-source="fileData" :row-selection="{ type: 'checkbox' }">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'docName'">
            <span style="display: flex; align-items: center; gap: 8px;">
              <span style="font-size: 18px; line-height: 1;">{{ getFileIcon(record.docType) }}</span>
              <span :title="record.docName" style="flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                {{ record.docName }}
              </span>
            </span>
          </template>
          <template v-else-if="column.key === 'createTime'">
            <span>{{ formatDateTime(record.createTime) }}</span>
          </template>
          <template v-else-if="column.key === 'enable'">
            <Switch 
              :checked="record.enable === 1 || record.enable === true || record.enable === undefined"
              @change="(checked) => handleEnableChange(record, checked)"
            />
          </template>
          <template v-else-if="column.key === 'chunkCount'">
            <span>{{ record.chunkCount || 0 }}</span>
          </template>
          <template v-else-if="column.key === 'parseStatus'">
            <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
              <span style="font-size: 14px;">{{ record.parseMethod || record.chunkingMethod || 'general' }}</span>
              <!-- 解析错误：显示红色圆点 -->
              <template v-if="record.parseError === true">
                <span style="width: 8px; height: 8px; border-radius: 50%; background-color: #ff4d4f; display: inline-block;" title="解析失败"></span>
              </template>
              <!-- 解析中：显示进度条和刷新图标 -->
              <template v-else-if="record.parseProgress != null && record.parseProgress > 0 && record.parseProgress < 100">
                <Progress 
                  :percent="record.parseProgress" 
                  :stroke-width="8" 
                  :show-info="true"
                  :format="(percent) => `${percent}%`"
                  style="width: 80px; margin: 0;"
                />
                <span style="color: #1890ff; font-size: 14px; cursor: pointer;" title="解析中">
                  🔄
                </span>
              </template>
              <!-- 解析完成：显示绿色对勾 -->
              <template v-else-if="record.parseProgress === 100 || (record.chunkCount && record.chunkCount > 0)">
                <span style="color: #52c41a; font-size: 12px;" title="解析完成">✓</span>
              </template>
              <!-- 未开始或进度为0：显示等待状态 -->
              <template v-else>
                <Progress 
                  :percent="0" 
                  :stroke-width="8" 
                  :show-info="false"
                  status="active"
                  style="width: 80px; margin: 0;"
                />
                <span style="color: #999; font-size: 12px;" title="等待解析">等待中</span>
              </template>
            </div>
          </template>
          <span v-else-if="column.key === 'action'">
            <Popconfirm
              title="确定删除吗？"
              ok-text="是"
              cancel-text="否"
              @confirm="handleDeleteFile(record)"
            >
              <Button type="primary" danger style="margin-right: 10px" size="small">
                删除
              </Button>
            </Popconfirm>

            <Button type="primary" @click="handleFragment(record)" size="small">
              知识片段
            </Button>
          </span>
        </template>
      </Table>
    </Drawer>

    <Drawer
      title="创建知识库"
      :visible="drawerVisible"
      @close="handleDrawerClose"
      :width="600"
      :footer-style="{ textAlign: 'right' }"
    >
      <Form
        :model="formData"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        ref="formRef"
      >
        <FormItem
          label="知识库名称"
          name="kname"
          :rules="[{ required: true, message: '请输入知识库名称' }]"
        >
          <Input v-model:value="formData.kname" placeholder="请输入知识库名称" />
        </FormItem>
        <FormItem label="知识描述" name="description">
          <Input 
            v-model:value="formData.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入知识库描述（可选）"
          />
        </FormItem>
        <FormItem
          label="是否公开"
          name="share"
          :rules="[{ required: true, message: '请选择是否公开' }]"
        >
          <RadioGroup v-model:value="formData.share">
            <Radio value="1">是</Radio>
            <Radio value="0">否</Radio>
          </RadioGroup>
        </FormItem>
        
        <div style="margin-top: 20px; padding: 15px; background-color: #f0f0f0; border-radius: 4px;">
          <p style="margin: 0; color: #666; font-size: 12px;">
            💡 提示：处理参数（分隔符、文本块大小等）在上传附件时配置
          </p>
        </div>
      </Form>
      <template #footer>
        <a-button style="margin-right: 8px" @click="handleDrawerClose"
          >取消</a-button
        >
        <a-button type="primary" @click="handleSubmit">添加</a-button>
      </template>
    </Drawer>

    <!-- 处理参数配置弹窗 -->
    <Drawer
      title="配置处理参数"
      :visible="processConfigVisible"
      @close="processConfigVisible = false"
      :width="600"
    >
      <Form
        :model="processConfig"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
      >
        <FormItem label="分隔符" name="separator">
          <Input 
            v-model:value="processConfig.separator" 
            placeholder="例如: \\n\\n\\n"
          />
        </FormItem>
        <FormItem label="文本块大小" name="textBlockSize">
          <InputNumber
            v-model:value="processConfig.textBlockSize"
            style="width: 100%"
            :min="1"
            :max="10000"
          />
        </FormItem>
        <FormItem label="重叠字符" name="overlapChar">
          <InputNumber
            v-model:value="processConfig.overlapChar"
            style="width: 100%"
            :min="0"
          />
        </FormItem>
        <FormItem label="检索条数" name="retrieveLimit">
          <InputNumber
            v-model:value="processConfig.retrieveLimit"
            style="width: 100%"
            :min="1"
          />
        </FormItem>
        <FormItem label="向量模型" name="vectorModel">
          <Select 
            v-model:value="processConfig.vectorModel" 
            :options="getVectorModel"
            style="width: 100%"
          />
        </FormItem>
        <FormItem label="提问分隔符" name="questionSeparator">
          <Input 
            v-model:value="processConfig.questionSeparator"
            placeholder="可选"
          />
        </FormItem>
        <FormItem label="切片方法" name="chunkingMethod">
          <Select 
            v-model:value="processConfig.chunkingMethod" 
            :options="chunkingMethodOptions"
            style="width: 100%"
          />
        </FormItem>
      </Form>
      <template #footer>
        <a-button @click="processConfigVisible = false">取消</a-button>
        <a-button type="primary" @click="processConfigVisible = false">
          确定
        </a-button>
      </template>
    </Drawer>
  </div>
</template>
